<template>
  <div class="toolbarVUe">
    <div class="toolbar flex-between">
      <!-- <el-select
        v-model="template"
        @change="changeTemplate"
        style="margin-right: 10px"
        placeholder="请选择"
      >
        <el-option
          v-for="item in Globaldata"
          :key="item.id"
          :label="item.templateName"
          :value="item.id"
        >
        </el-option>
      </el-select> -->

      <!-- <el-button @click="selectTemplate">选择模板</el-button> -->
      <div class="flex" >
        <div class="flex" style="margin-right: 10px">
          <el-select
            v-model="pageValue"
            @change="changepage"
            placeholder="请选择预览界面"
          >
            <el-option
              v-for="item in globelPage"
              :key="item.name"
              :label="item.pagename"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </div>
        <el-button @click="undo" style="margin-right: 10px">撤消</el-button>
        <!-- <el-button @click="addMoban">导入模板</el-button> -->
        <el-upload
          class="avatar-uploader"
          action=""
          style="margin-right: 10px"
          v-model="Addfrom.url"
          :show-file-list="false"
          :http-request="uploadURL2"
          :multiple="true"
          :before-upload="handleBeforeUpload"
        >
          <el-button size="small">导入模板</el-button>
        </el-upload>
        <!-- <label for="input" class="insert">插入图片</label>
            <input
                id="input"
                type="file"
                hidden
                @change="handleFileChange"
            /> -->

        <!-- <Upload @confrim="confrim" :type="''" :text="'插入图片'"></Upload> -->

        <!-- <el-button @click="saveTemplate">保存模板</el-button> -->
        <el-button size="small" @click="daochu" v-if="daochu_bool">导出模板</el-button>
        <el-button @click="clearCanvas">清空画布</el-button>
        <!-- <el-button @click="fabuJson">发布</el-button> -->
        <el-button :disabled="!areaData.components.length" @click="compose"
          >组合</el-button
        >
        <el-button
          :disabled="
            !curComponent ||
            curComponent.isLock ||
            curComponent.component != 'Group'
          "
          @click="decompose"
        >
          拆分
        </el-button>

        <el-button
          :disabled="!curComponent || curComponent.isLock"
          @click="lock"
          >锁定</el-button
        >
        <el-button
          :disabled="!curComponent || !curComponent.isLock"
          @click="unlock"
          >解锁</el-button
        >
        <div class="canvas-config">
          <span>画布大小</span>
          <input @blur="setconfigStyle" v-model="canvasStyleData.width" />
          <span>*</span>
          <input @blur="setconfigStyle" v-model="canvasStyleData.height" />
        </div>
        <div class="canvas-config">
          <span>画布比例</span>
          <input v-model="scale" @input="handleScaleChange" /> %
        </div>
      </div>
      <div class="flex" style="padding-right: 20px;">
        <el-button @click="saveSHOW">保存</el-button>
        <el-button style="margin-left: 10px" @click="preview">预览</el-button>
      </div>
    </div>

    <!-- 预览 -->
    <div class="preview_dialog_box">
      <el-dialog
        title="预览"
        :visible.sync="isShowPreview"
        append-to-body
        width="1920px"
        fullscreen
        custom-class="previewDialog"
        style="height: 100vh"
      >
        <Preview
          style="height: 100%"
          @closeTK="closeTK"
          @change="handlePreviewChange"
        />
      </el-dialog>
    </div>

    <el-dialog title="保存" :visible.sync="Savedialog" width="40%">
      <el-form label-width="120px">
        <el-form-item label="页面名称(xxx.html)">
          <el-input v-model="pagefrom.name"></el-input>
        </el-form-item>
        <el-form-item label="名称(首页)">
          <el-input v-model="pagefrom.pagename"></el-input>
        </el-form-item>
        <el-form-item class="flex-end">
          <el-button type="primary" size="small" @click="save">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="保存模板" :visible.sync="TemplateDialog" width="40%">
      <SetTemplate
        @closeTK="closeTK"
        :id="templateId"
        v-if="TemplateDialog"
      ></SetTemplate>
      <!-- <el-form label-width="120px">
        <el-form-item label="模板首页">
          <el-input v-model="Temfrom.HomepageName" readonly></el-input>
        </el-form-item>
         <el-form-item label="模板图片">
          <div class="flex">
            <el-input v-model="Temfrom.templateImg"></el-input>
            <Upload :type="'primary'" @confrim="confrimTemplate" :text="'上传图片'"></Upload>
          </div>
        </el-form-item>
        <el-form-item label="模板名称">
          <el-input v-model="Temfrom.templateName"></el-input>
        </el-form-item>
        <el-form-item label="模板创建人">
          <el-input v-model="Temfrom.userName"></el-input>
        </el-form-item>
        <el-form-item class="flex-end">
          <el-button type="primary" size="small" @click="Templatesave"
            >确定</el-button
          >
        </el-form-item>
      </el-form> -->
    </el-dialog>

    <el-dialog title="模板选择" :visible.sync="templateMoudels" width="1200px">
      <TemplateMoudel
        v-if="templateMoudels"
        :Globaldata="Globaldata"
        @closeTK="closeTK"
      ></TemplateMoudel>
    </el-dialog>

    <el-dialog title="自定义组件" :visible.sync="customBool" width="500px">
      <el-form size="small" label-width="80px">
        <el-form-item label="名称">
          <el-input
            v-model="formLabelAlign.componentsAutomaticallyName"
          ></el-input>
        </el-form-item>
        <el-form-item label="权重">
          <el-input v-model="formLabelAlign.sort" type="number"></el-input>
        </el-form-item>
        <el-form-item class="flex-end">
          <el-button type="" size="small">取消</el-button>
          <el-button type="primary" size="small" @click="templateOK"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import generateID from "@/utils/generateID";
import FileSaver from "file-saver";
import toast from "@/utils/toast";
import { mapState } from "vuex";
import Preview from "@/components/Editor/Preview";
import { commonStyle, commonAttr } from "@/custom-component/component-list";
import eventBus from "@/utils/eventBus";
import { deepCopy } from "@/utils/utils";
import { divide, multiply, resolve } from "mathjs";
import { changeStyleWithScale } from "@/utils/translate";
import axios from "axios";
import Upload from "../components/Upload/index.vue";
import { json } from "body-parser";
import { client, getFileNameUUID } from "./Upload/alioss.js";
import { async, reject } from "q";
import SetTemplate from "./TemplateMoudel/SetTemplate.vue";
import TemplateMoudel from "./TemplateMoudel/TemplateMoudel.vue";
import api from "@/api/models/api.js";
export default {
  components: { Preview, Upload, TemplateMoudel, SetTemplate },
  data() {
    return {
      globelPage: JSON.parse(localStorage.getItem("GlobalcanvasData")),
      pageValue: localStorage.getItem("page")
        ? localStorage.getItem("page")
        : "",
      isShowPreview: false,
      daochu_bool:!!JSON.parse(localStorage.getItem("GlobalcanvasData")),
      TemplateDialog: false,
      templateMoudels: false,
      customBool: false,
      Savedialog: false,
      templateId: localStorage.getItem("templateNameId"),
      template: localStorage.getItem("templateName"),
      pagefrom: {
        name: localStorage.getItem("page") ? localStorage.getItem("page") : "",
        pagename: localStorage.getItem("pageName")
          ? localStorage.getItem("pageName")
          : "",
      },
      Globaldata: [],
      Temfrom: {
        globalcanvasData: "",
        canvasData: "",
        type: 1,
        isPassword: 1,
        password: "",
        templateName: this.$route.query.name,
        templateImg: "",
        updateBy: "",
      },
      needToChange: ["top", "left", "width", "height", "fontSize"],
      scale: "100%",
      timer: null,
      combinationItem: {},
      formLabelAlign: {
        componentsAutomaticallyName: "",
        sort: 1,
      },
      EDITMOBAN: false,
      fileList: [],
      Addfrom: {
        url: "",
      },
    };
  },
  computed: mapState([
    "componentData",
    "canvasStyleData",
    "areaData",
    "curComponent",
    "curComponentIndex",
  ]),
  created() {
    this.init();
    eventBus.$on("preview", this.preview);
    eventBus.$on("save", this.save);
    eventBus.$on("clearCanvas", this.clearCanvas);
    this.scale = this.canvasStyleData.scale;
  },
  mounted() {
    this.$EventBus.$on("HtmlHeight", (e) => {
      this.$store.commit("setCanvasStyleHeight", e);
      let canvasStyle = JSON.parse(localStorage.getItem("canvasStyle"));
      canvasStyle.height = String(e);
      localStorage.setItem("canvasStyle", JSON.stringify(canvasStyle));
    });

    this.$EventBus.$on("combination", (e) => {
      this.combinationItem = e;
    });
  },
  methods: {
    selectTemplate() {
      this.templateMoudels = true;
    },
    daochu(){
        const data = localStorage.getItem("GlobalcanvasData");
        const templateNmae = localStorage.getItem("templateName");
        const blob = new Blob([data], { type: "application/json" });
        FileSaver.saveAs(blob, `${templateNmae}.json`)
    },
    changepage(e) {
      console.log(e);
      let globalData = JSON.parse(localStorage.getItem("GlobalcanvasData"));
      for (let key in globalData) {
        if (globalData[key].name == e) {
          // setComponentData
          this.$store.commit("setComponentData", globalData[key].canvasData);
          localStorage.setItem("downloadPage", globalData[key].name);
          this.pagefrom.name=globalData[key].name
          this.pagefrom.pagename=globalData[key].pagename
          localStorage.setItem("page", globalData[key].name);
          localStorage.setItem("pageName", globalData[key].pagename);
          localStorage.setItem('canvasStyle',JSON.stringify(globalData[key].canvasStyle) )
          this.$store.commit("setCanvasStyle", globalData[key].canvasStyle);
          localStorage.setItem(
            "canvasData",
            JSON.stringify(this.$store.state.componentData)
          );
          // this.pageValue=globalData[key].name
        }
      }
    },

    handleBeforeUpload(file) {
      const isJson = file.name.split(".")[1] === "json";
      const isLt500K = file.size / 1024 / 1024 < 10;
      if (!isJson) {
        this.$message.error("上传文件只能是 JSON 格式!");
      }
      if (!isLt500K) {
        this.$message.error("文件大小不能超过 5mb!");
      }
      return isJson && isLt500K;
    },
    async uploadURL2(file) {
      this.$confirm("导入模板会覆盖当前模板数据, 请确认继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var fileName = "json/" + this.$route.query.id + "_" + file.file.name;
          //定义唯一的文件名，打印出来的uid其实就是时间戳
          client()
            .multipartUpload(fileName, file.file, {
              progress: function (percentage, cpt) {
                console.log("打印进度", percentage);
              },
            })
            .then(async (res) => {
              console.log(res, "上传成功");
              //此处赋值，是相当于上传成功之后，手动拼接服务器地址和文件名
              let url =
                "https://ejarwebtools.oss-cn-hangzhou.aliyuncs.com/" + res.name;
              let GlobaleCanvasData = await this.getJSON(url);
              let canvasData = GlobaleCanvasData[0].canvasData;
              localStorage.setItem("canvasData", JSON.stringify(canvasData));
              this.$store.commit("setComponentData", canvasData);
              localStorage.setItem(
                "GlobalcanvasData",
                JSON.stringify(await GlobaleCanvasData)
              );
              this.$message.success("导入成功！");
              this.globelPage = JSON.parse(
                localStorage.getItem("GlobalcanvasData")
              );
              this.pageValue = GlobaleCanvasData[0].name;
            });
        })
        .catch(() => {
          return false;
        });
      //注意哦，这里指定文件夹'image/'，尝试过写在配置文件，但是各种不行，写在这里就可以
    },

    fabuJson() {
      const data = localStorage.getItem("GlobalcanvasData");
      const blob = new Blob([data], { type: "application/json" });
      // FileSaver.saveAs(blob, `GlobalcanvasData.json`)
      this.uploadURL(blob, "GlobalcanvasData.json");
    },
    async uploadURL(file, name) {
      return new Promise((resolve, reject) => {
        var fileName = "json/" + name;
        //定义唯一的文件名，打印出来的uid其实就是时间戳
        client()
          .multipartUpload(fileName, file, {
            progress: function (percentage, cpt) {
              console.log("打印进度", percentage);
            },
          })
          .then((res) => {
            console.log(res, "上传成功");
            //此处赋值，是相当于上传成功之后，手动拼接服务器地址和文件名
            let url =
              "https://ejarwebtools.oss-cn-hangzhou.aliyuncs.com/" + res.name;
            console.log(url);
            resolve(url);
          });
      });
    },
    init() {
      // axios.post("http://api.hweihong.top/template/getTemplateList").then((res) => {
      //   console.log(res, "321321321");
      //   this.Globaldata = res.data.data;
      // });
      api.getTemplateList().then((res) => {
        this.Globaldata = res.data.records;
      });
    },
    async getJSON(url) {
      return new Promise((resolve, reject) => {
        $.get(url, function (data) {
          resolve(data);
          return;
        });
      });
    },
    changeTemplate(e) {
      axios({
        url: "http://api.hweihong.top/getCanvasData",
        method: "POST",
        data: { id: e },
      }).then(async (res) => {
        let Globaldata = res.data.data;
        //  console.log( Globaldata[0].canvasData)
        let GlobalcanvasData = await this.getJSON(
          Globaldata[0].GlobalcanvasData
        );
        let canvasData = await this.getJSON(Globaldata[0].canvasData);
        // console.log(Globaldata);
        // var json_str = Globaldata[0].canvasData
        //   .replace(/\n/g, "\\n")
        //   .replace(/\r/g, "\\r");
        // var t_obj = eval("(" + json_str + ")");
        // var json_str2 = Globaldata[0].GlobalcanvasData.replace(
        //   /\n/g,
        //   "\\n"
        // ).replace(/\r/g, "\\r");
        // var t_obj2 = eval("(" + json_str2 + ")");
        if (Globaldata.length && Globaldata[0].GlobalcanvasData) {
          localStorage.setItem("canvasData", JSON.stringify(canvasData));
          localStorage.setItem(
            "GlobalcanvasData",
            JSON.stringify(GlobalcanvasData)
          );
          localStorage.setItem("templateName", Globaldata[0].templateName);
          localStorage.setItem("templateNameId", e);
          this.$store.commit("setComponentData", canvasData);
        }
      });
    },
    async Templatesave() {
      const GlobalcanvasData = localStorage.getItem("GlobalcanvasData");
      const canvasData = localStorage.getItem("canvasData");
      const Bigblob = new Blob([GlobalcanvasData], {
        type: "application/json",
      });
      const Indexblob = new Blob([canvasData], { type: "application/json" });
      // FileSaver.saveAs(blob, `GlobalcanvasData.json`)
      this.Temfrom.GlobalcanvasData = await this.uploadURL(
        Bigblob,
        this.Temfrom.templateName + ".json"
      );
      this.Temfrom.canvasData = await this.uploadURL(
        Indexblob,
        this.Temfrom.HomepageName + ".json"
      );

      this.$confirm("保存模板前请已经确认页面预览正确", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (this.Temfrom.GlobalcanvasData && this.Temfrom.canvasData) {
          axios({
            method: "post",
            url: "http://api.hweihong.top/saveCanvasData",
            data: {
              ...this.Temfrom,
              id: localStorage.getItem("templateNameId"),
            },
          }).then((res) => {
            this.TemplateDialog = false;
          });
        }
      });
    },
    confrimTemplate(e) {
      this.Temfrom.templateImg = e;
    },
    confrim(e) {
      let _this = this;
      console.log(e, "接受url");
      const img = new Image();
      img.onload = () => {
        _this.$store.commit("addComponent", {
          component: {
            ...commonAttr,
            id: generateID(),
            component: "Picture",
            label: "图片",
            icon: "",
            propValue: e,
            style: {
              ...commonStyle,
              top: 0,
              left: 0,
              width: img.width,
              height: img.height,
            },
          },
        });

        _this.$store.commit("recordSnapshot");
      };

      img.src = e;
    },
    format(value) {
      return multiply(value, divide(parseFloat(this.scale), 100));
    },
    setconfigStyle() {
      let canvasStyle = JSON.parse(localStorage.getItem("canvasStyle"));
      canvasStyle.height = String(this.canvasStyleData.height);
      canvasStyle.width = String(this.canvasStyleData.width);
      localStorage.setItem("canvasStyle", JSON.stringify(canvasStyle));
    },

    getOriginStyle(value) {
      return divide(value, divide(parseFloat(this.canvasStyleData.scale), 100));
    },
    closeTK() {
      this.isShowPreview = false;
      this.templateMoudels = false;
      this.TemplateDialog = false;
    },

    handleScaleChange() {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        // 画布比例设一个最小值，不能为 0
        // eslint-disable-next-line no-bitwise
        this.scale = ~~this.scale || 1;
        const componentData = deepCopy(this.componentData);
        componentData.forEach((component) => {
          Object.keys(component.style).forEach((key) => {
            if (this.needToChange.includes(key)) {
              // 根据原来的比例获取样式原来的尺寸
              // 再用原来的尺寸 * 现在的比例得出新的尺寸
              component.style[key] = this.format(
                this.getOriginStyle(component.style[key])
              );
            }
          });
        });

        this.$store.commit("setComponentData", componentData);
        // 更新画布数组后，需要重新设置当前组件，否则在改变比例后，直接拖动圆点改变组件大小不会生效 https://github.com/woai3c/visual-drag-demo/issues/74
        this.$store.commit("setCurComponent", {
          component: componentData[this.curComponentIndex],
          index: this.curComponentIndex,
        });
        this.$store.commit("setCanvasStyle", {
          ...this.canvasStyleData,
          scale: this.scale,
        });
      }, 1000);
    },

    lock() {
      this.$store.commit("lock");
    },

    unlock() {
      this.$store.commit("unlock");
    },
    async templateOK() {
      this.$store.commit("compose");
      this.$store.commit("recordSnapshot");
      setTimeout(() => {
        if (this.combinationItem) {
          let data = this.combinationItem;
          data.type = "custom";
          data.label = this.formLabelAlign.componentsAutomaticallyName;
          data.icon = "button";
          //  let item={name:this.formLabelAlign.name,componentsAutomaticallyData:data}
          api
            .addComponentsAutomatically({
              ...this.formLabelAlign,
              componentsAutomaticallyData: data,
            })
            .then(async (res) => {
              if (res.code == "200") {
                this.$message.success(res.data || res.msg);
                this.customBool = false;
                location.reload();
              } else {
                this.$message.error(res.message || res.msg);
              }
            });
        }
      }, 200);
    },
    compose() {
      this.$confirm("是否添加进我的自定义组件", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          this.customBool = true;
        })
        .catch(() => {
          this.$store.commit("compose");
          this.$store.commit("recordSnapshot");
        });
    },

    decompose() {
      this.$store.commit("decompose");
      this.$store.commit("recordSnapshot");
    },

    undo() {
      this.$store.commit("undo");
    },

    redo() {
      this.$store.commit("redo");
    },

    handleFileChange(e) {
      const file = e.target.files[0];
      if (!file.type.includes("image")) {
        toast("只能插入图片");
        return;
      }
      let _this = this;
      let param = new FormData(); // 创建form对象
      //注意files是对应后台的参数名哦
      param.append("file", file); // 通过append向form对象添加数据

      const reader = new FileReader();
      reader.onload = (res) => {
        axios
          .post(this.$uploadUrl, param, {
            "Content-type": "multipart/form-data",
          })
          .then((response) => {
            const fileResult = response.data.data;
            console.log(fileResult);
            const img = new Image();
            img.onload = () => {
              _this.$store.commit("addComponent", {
                component: {
                  ...commonAttr,
                  id: generateID(),
                  component: "Picture",
                  label: "图片",
                  icon: "",
                  propValue: fileResult,
                  style: {
                    ...commonStyle,
                    top: 0,
                    left: 0,
                    width: img.width,
                    height: img.height,
                  },
                },
              });

              _this.$store.commit("recordSnapshot");

              // 修复重复上传同一文件，@change 不触发的问题
              document.querySelector("#input").setAttribute("type", "text");
              document.querySelector("#input").setAttribute("type", "file");
            };

            img.src = fileResult;
          });
        // const fileResult = res.target.result
      };

      reader.readAsDataURL(file);
    },

    preview() {
      // this.isShowPreview = true;
      this.$confirm("预览前请先保存, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$store.commit("setEditMode", "preview");
          if (this.$route.query.type == 1) {
            this.$router.push("/preview");
          } else {
            this.$router.push("/MobilePreview");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    saveSHOW() {
      this.Savedialog = true;
      // localStorage.setItem('canvasData', JSON.stringify(this.componentData))
      // localStorage.setItem('canvasStyle', JSON.stringify(this.canvasStyleData))
      // this.$message.success('保存成功')
    },
    async saveTemplate() {
      if (!this.templateId) {
        this.$message.error("保存模板出错,未找到id!");
        return;
      }
      // this.TemplateDialog = true;
      const GlobalcanvasData = localStorage.getItem("GlobalcanvasData");
      const canvasData = localStorage.getItem("canvasData");
      const Bigblob = new Blob([GlobalcanvasData], {
        type: "application/json",
      });
      const Indexblob = new Blob([canvasData], { type: "application/json" });
      // FileSaver.saveAs(blob, `GlobalcanvasData.json`)
      this.Temfrom.globalcanvasData = await this.uploadURL(
        Bigblob,
        this.Temfrom.templateName + "_globale" + ".json"
      );
      this.Temfrom.canvasData = await this.uploadURL(
        Indexblob,
        this.Temfrom.templateName + "_index" + ".json"
      );
      this.$confirm("保存模板前请已经确认页面预览正确", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (this.Temfrom.globalcanvasData && this.Temfrom.canvasData) {
          api
            .saveTemplate({
              ...this.Temfrom,
              id: this.templateId ? this.templateId : "",
            })
            .then((res) => {
              console.log(res);
              if (res.code == 200) {
                this.$emit("closeTK");
              } else {
                this.$message.error(res.msg || res.message);
              }
            });
        }
      });
    },
    getMappingValueArrayOfKey(array, keyName) {
      if (Object.prototype.toString.call(array) == "[object Array]") {
        return array.map((item, index) => {
          return item[keyName];
        });
      }
      return "null（参数一应为对象数组）"; //不是数组
    },
    async save() {
      if (this.pagefrom.name) {
        localStorage.setItem("page", this.pagefrom.name);
      }
      if (this.pagefrom.pagename) {
        localStorage.setItem("pageName", this.pagefrom.pagename);
      }
      let page = this.pagefrom.name
        ? this.pagefrom.name
        : localStorage.getItem("page");
      let pagename = this.pagefrom.pagename
        ? this.pagefrom.pagename
        : localStorage.getItem("pageName");
      if (!page) {
        this.$message.error("第一次请先保存该页面名称");
        return;
      }
      let canvasData = (await JSON.parse(
        localStorage.getItem("GlobalcanvasData")
      ))
        ? JSON.parse(localStorage.getItem("GlobalcanvasData"))
        : [];
      let keys = await this.getMappingValueArrayOfKey(canvasData, "name");
      if (canvasData.length) {
        for (let key in canvasData) {
          if (keys.includes(page)) {
            if (canvasData[key].name == page) {
              canvasData[key].canvasData = this.componentData;
              canvasData[key].pagename = pagename;
              canvasData[key].canvasStyle = this.canvasStyleData;
            }
          } else {
            keys.push(page);
            await canvasData.push({
              name: page,
              canvasData: this.componentData,
              canvasStyle: this.canvasStyleData,
              pagename: pagename,
            });
          }
        }
      } else {
        await canvasData.push({
          name: page,
          canvasData: this.componentData,
          canvasStyle: this.canvasStyleData,
          pagename: pagename,
        });
      }

      console.log(await canvasData);
      localStorage.setItem(
        "GlobalcanvasData",
        JSON.stringify(await canvasData)
      );
      localStorage.setItem("canvasData", JSON.stringify(this.componentData));
      localStorage.setItem("canvasStyle", JSON.stringify(this.canvasStyleData));
      localStorage.setItem("downloadPage", page);
      this.$message.success("保存成功");
      this.Savedialog = false;

      this.saveTemplate();
    },

    clearCanvas() {
      localStorage.setItem("canvasData", []);
      localStorage.setItem("pageName", "");
      localStorage.setItem("page", "");
      localStorage.setItem("fromKeyList", "");
      localStorage.removeItem("fromKeyList");
      this.$store.commit("setCurComponent", { component: null, index: null });
      this.$store.commit("setComponentData", []);
      this.$store.commit("recordSnapshot");
      setTimeout(() => {
        location.reload();
      }, 10);
    },

    handlePreviewChange() {
      this.$store.commit("setEditMode", "edit");
    },
  },
};
</script>
<style>
.previewDialog .el-dialog__body {
  height: 100% !important;
  padding: 0;
}
</style>
<style lang="scss" scoped>
.toolbar {
  padding: 15px 10px;
  white-space: nowrap;
  overflow-x: auto;
  background: #fff;
  border-bottom: 1px solid #ddd;

  .canvas-config {
    display: inline-block;
    margin-left: 10px;
    font-size: 14px;
    color: #606266;

    input {
      width: 50px;
      margin-left: 10px;
      outline: none;
      padding: 0 5px;
      border: 1px solid #ddd;
      color: #606266;
    }

    span {
      margin-left: 10px;
    }
  }

  .insert {
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    background: #fff;
    border: 1px solid #dcdfe6;
    color: #606266;
    -webkit-appearance: none;
    text-align: center;
    box-sizing: border-box;
    outline: 0;
    margin: 0;
    transition: 0.1s;
    font-weight: 500;
    padding: 9px 15px;
    font-size: 12px;
    border-radius: 3px;
    margin-left: 10px;

    &:active {
      color: #3a8ee6;
      border-color: #3a8ee6;
      outline: 0;
    }

    &:hover {
      background-color: #ecf5ff;
      color: #3a8ee6;
    }
  }
}
</style>
